'use strict';
const semver = require('semver');
const colors = require('colors');
const path = require('path');
const userHome = require('user-home');
// import semver from 'semver';
// import colors from 'colors';
// import path from 'path';
// import userHome from 'user-home';

// import {
//   pathExists,
//   pathExistsSync
// } from 'path-exists';
const log = require('@ymh-cli/log');
// import * as log from '@ymh-cli/log'


let argv, config;
const pkg = require('../package.json');
const constant = require('./const');
// import constant from './const.js'

function core (cwd) {
  try {
    log.verbose("根目录", userHome)
    checkInputArgs();
    checkUserHome()
    checkRoot();
    checkPkgVersion();
    checkNodeVersion();
    // checkEnv();
    checkGlobalsUpdate();
  } catch (error) {
    log.error(error.message);
  }
}
function checkEnv () {
  const dotEnv = require('dotenv');
  const dotEnvPath = path.resolve(userHome, '.ymh-cli.env')
  if (pathExists(dotEnvPath)) {
    config = dotEnv.config({
      path: dotEnvPath
    });
  }
  createdDefaultConfig();
  log.verbose("环境变量", config, process.env.CLI_HOME_PATH)
}

function createdDefaultConfig () {
  const cliConfig = {
    home: userHome,
  }
  if (process.env.CLI_HOME) {
    cliConfig["cliHome"] = path.join(userHome, process.env.CLI_HOME)
  } else {
    cliConfig["cliHome"] = path.join(userHome, constant.DEFAULT_CLI_HOME)
  }
  process.env.CLI_HOME_PATH = cliConfig['cliHome']
}

function checkInputArgs () {
  argv = require('minimist')(process.argv.slice(2));
  console.log(argv);
  checkArgs();
}

function checkArgs () {
  if (argv.debug) { //
    process.env.LOG_LEVEL = "verbose";
  } else {
    process.env.LOG_LEVEL = "info";
  }
  log.level = process.env.LOG_LEVEL;
}

function checkUserHome () {
  // console.log( import('path-exists'))
  // if (!userHome || pathExistsSync(userHome)) {
  //   throw new Error(colors.red("当前登录用户主目录不存在!"));
  // }
  // log.notice('cli', pkg.version);
}

function checkRoot () {
  // console.log(process.geteuid());
  // const { rootCheck } = await import('root-check');
  // // import { pathExistsSync } from 'path-exists';
  // // rootCheck();
  // log.notice('rootCheck', rootCheck());
}

function checkPkgVersion () {
  // console.log('Checking', pkg.version);
  log.notice('cli', pkg.version);
}

function checkNodeVersion () {
  //1、获取当前版本号
  const currentVersion = process.version;
  const lowestVersion = constant.LOWEST_NODE_VERSION;
  //2、判断是否大于最低版本号
  if (!semver.gte(currentVersion, lowestVersion)) {
    throw new Error(colors.red("需要安装" + lowestVersion + "以上的node.js版本方可使用"));
  } else {

  }

  log.notice('node', process.version);
}


function checkGlobalsUpdate () {
  //1、获取当前版本号、模块名
  const currentVersion = pkg.version;
  const moduleName = pkg.name;
  //2、调用 npm API ,获取所有版本号

  //3、提取所有版本号、对比哪些版本号是否大于当前版本号
  //4、获取最新版本号、提示用户是否更新到该版本
}


module.exports = core;